import { TrainRecordDao } from '../dao/trainRecordDao';
import { PageReq, Page } from '../../types/page';
import { TrainRecord } from '../../types/trainRecord';

export class TrainRecordService {
  // 新增训练记录
  static async add(record: Omit<TrainRecord, 'id'>): Promise<number> {
    return await TrainRecordDao.add(record);
  }

  // 更新训练记录
  static async update(record: TrainRecord): Promise<void> {
    await TrainRecordDao.update(record);
  }

  // 删除训练记录
  static async delete(id: number): Promise<void> {
    await TrainRecordDao.delete(id);
  }

  // 根据ID查询
  static async getById(id: number): Promise<TrainRecord | null> {
    return await TrainRecordDao.getById(id);
  }

  // 查询所有记录
  static async getAll(): Promise<TrainRecord[]> {
    return await TrainRecordDao.getAll();
  }

  // 分页查询
  static async getPage(pageReq: PageReq<Partial<TrainRecord>>): Promise<Page<TrainRecord>> {
    // 构建查询条件
    const conditions: string[] = [];
    const params: any[] = [];
    
    if (pageReq.params.course_id) {
      conditions.push('course_id = ?');
      params.push(pageReq.params.course_id);
    }
    if (pageReq.params.slot_id) {
      conditions.push('slot_id = ?');
      params.push(pageReq.params.slot_id);
    }
    if (pageReq.params.trainer_id) {
      conditions.push('trainer_id = ?');
      params.push(pageReq.params.trainer_id);
    }
    if (pageReq.params.scense_id) {
      conditions.push('scense_id = ?');
      params.push(pageReq.params.scense_id);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM train_record ${whereClause}`;
    const totalResult = await TrainRecordDao.getCount(countSql, params);

    // 查询分页数据
    const offset = (pageReq.pageNum - 1) * pageReq.pageSize;
    const querySql = `SELECT * FROM train_record ${whereClause} LIMIT ? OFFSET ?`;
    const queryParams = [...params, pageReq.pageSize, offset];
    const list = await TrainRecordDao.query(querySql, queryParams);

    return {
      total: totalResult.total,
      list
    };
  }
}